package com.mybatis.study.session.impl;

import java.lang.reflect.Proxy;
import java.util.List;

import com.mybatis.study.binding.MapperProxy;
import com.mybatis.study.config.Configuration;
import com.mybatis.study.config.MapperStatement;
import com.mybatis.study.executor.DefaultExecutor;
import com.mybatis.study.executor.Executor;
import com.mybatis.study.session.SqlSession;

/**
 * mybatis暴露给外部接口，实现增删改查
 * 
 * 1 对外提供数据服务的API
 * 2 对内部请求转发的executor
 * @author hzhm0002
 *
 */
public class DefaultSqlSession implements SqlSession {
	
	private final Configuration config;
	
	private Executor executor;

	public DefaultSqlSession(Configuration config) {
		super();
		this.config = config;
		executor=new DefaultExecutor(config);
	}

	public <T> T selectOne(String statement, Object paramter) {
		// TODO Auto-generated method stub
		MapperStatement mapperStatement=config.getMapperStatementMap().get(statement);
		List<T> list=executor.query(mapperStatement, paramter);
		if(list==null || list.size()==0) {
			return null;
		}
		if(list.size()==1) {
			return list.get(0);
		}else {
			throw new RuntimeException("too many");
		}
	
	}

	public <E> List<E> selectList(String statement, Object paramter) {
		MapperStatement mapperStatement=config.getMapperStatementMap().get(statement);
		return executor.query(mapperStatement, paramter);
	}

	/**
	 * 使用动态代理，类加载器，实现类的
	 * proxy
	 */
	public <T> T getMapper(Class<T> type) {
		// TODO Auto-generated method stub
		MapperProxy mp=new MapperProxy(this);
		return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, mp);
	}

}
